from django.db import connection

from libs.common import error, success
from libs.db import DB


def order_board(request):
    order_sn = request.GET.get('order_sn', default='')
    if order_sn == '':
        return error('无效的订单号')
    with connection.cursor() as cursor:
        cs_order_db = DB('cs_orders', conn=cursor)
        cs_order_fields = ['id', 'shop_id', 'cashier_id', 'order_sn', 'bill_num',
                           'pay_method', 'member_id', 'account', 'goods_num', 'return_num',
                           'return_order_sn', 'total_price', 'cart_total_price', 'remark', 'assoc_order_id',
                           'cart_typ', 'coupon_status', 'amount_sign', 'status', 'trade_state_desc',
                           'created', 'updated', 'deleted']
        db_cs_order = cs_order_db.one(cs_order_fields, 'order_sn=%s', [order_sn])
        resp_data = {'cs_order': db_cs_order}
        shop_id = db_cs_order.get('shop_id', 0)
        if shop_id > 0:
            shop_db = DB('table_shop_address', conn=cursor)
            shop_fields = ['id', 'shop_name', 'shop_phone', 'shop_address']
            db_shop = shop_db.one(shop_fields, 'id=%s', [shop_id])
            if db_shop.get('id', 0) > 0:
                resp_data.update({'shop': db_shop})
        cashier_id = db_cs_order.get('shop_id', 0)
        if cashier_id > 0:
            cashier_db = DB('cs_admins', conn=cursor)
            cashier_fields = ['id', 'shop_id', 'role_id', 'device_code', 'job_num',
                              'username', 'tel', 'status', 'last_login_at', 'last_logout_at']
            db_cashier = cashier_db.one(cashier_fields, 'id=%s', [cashier_id])
            if db_cashier.get('id', 0) > 0:
                resp_data.update({'cashier': db_cashier})
        order_detail_db = DB('cs_order_details', conn=cursor)
        order_detail_fields = ['id', 'order_id', 'goods_id', 'goods_name', 'barcode',
                               'amount', 'selling_price', 'spec_typ', 'is_input_price', 'is_discount',
                               'subtotal_raw', 'subtotal', 'stock_prev', 'stock_next', 'return_num',
                               'return_order_id', 'stock_log_id', 'status', 'created', 'updated',
                               'deleted']
        db_cs_order_id = db_cs_order.get('id', 0)
        db_order_detail_arr = order_detail_db.find(order_detail_fields, 'order_id=%s', [db_cs_order_id])
        resp_data.update({'order_detail': db_order_detail_arr})
        return success(**resp_data)
